import React from 'react';
import {Router, Route, Link} from 'react-router';

import utils from '../js/utils';

class Index extends React.Component {
  constructor () {
    super();

    this.state = {
      adminid: 0,
      openid: '',
      nickname: '',
      headimgurl: '',
      user_no: '',

      pay_status: true,

      confirm_status: false,
      confirm_msg: '',
      

      huiyuan_list: [],
      select_huiyuan_idx: 0, // 当前所选择的某个会员序号 idx
      huiyuan_quanyi: [], // 当前选择会员的权益内容，通过字符串转变为数组，然后循环展示在页面
    }
  }

  componentDidMount () {
    let app_id = this.props.params.app_id;
    let unionid = this.props.params.unionid;
    let _this = this;

    // 检查是否是微信浏览器，当unionid为空时，跳转授权登录页面
    utils.checkIsWeixin(app_id, unionid);
    // 处理用户分享
    utils.common_post("/get_app_share", {app_id, unionid}, function (res) {
      _this.setState({
        adminid: res.adminid,
        user_no: res.user_no,
        openid: res.openid,
        nickname: res.nickname,
        headimgurl: res.headimgurl
      })
      $("title").text(res.app_name + "VIP会员")
      var sharetitle = res.app_name;
      var sharedesc = res.app_share_title;
      var shareimg = "https://ke.juzizhi.cn" + res.app_share_litpic;
      var sharelink = 'https://ma.ke.juzizhi.cn?s=friend_share&friend_unionid='+ unionid +'#/' + app_id;
      utils.weixinShare(sharetitle,sharelink,sharedesc,shareimg);
    })
    utils.common_post("/get_tiku_huiyuan", {app_id, unionid}, function (res) {
      let list = res.list;
      for (let i = 0, len = list.length; i < len; i++) {
        if (list[i].ma_time_len == 0) {
          list[i].yuan = (list[i].price / 36135).toFixed(2)
        }
        else {
          list[i].yuan = (list[i].price / list[i].ma_time_len).toFixed(2)
        }
      }
      _this.setState({
        huiyuan_list: list,
        select_huiyuan_id: res.list[0]['_id']['$oid'],
        huiyuan_quanyi: res.list[0].description.split(/\,|\，/)
      })
    })
  }

  changeHuiyuan (e) {
    let ele = e.currentTarget;
    let id = $(ele).attr('data-id');
    let idx = parseInt($(ele).attr('data-idx'), 10)
    console.log(id, idx)
    this.setState({
      select_huiyuan_id: id,
      select_huiyuan_idx: idx
    })
  }

  Pay () {

    let huiyuan_id = this.state.select_huiyuan_id;
    let app_id = this.props.params.app_id;
    let unionid = this.props.params.unionid;
    let adminid = this.state.adminid;
    let openid = this.state.openid

    let data = {
      adminid,
      app_id,
      unionid,
      huiyuan_id,
      openid
    }

    let _this = this;

    utils.pay_post("/shop_pay", data, function (res) {

      if (parseInt(res.code, 10) == 200) {
        let r = res.r;
        WeixinJSBridge.invoke('getBrandWCPayRequest', {
          "appId": r.appId,     //公众号ID，由商户传入     
          "timeStamp": r.timeStamp,     //时间戳，自1970年以来的秒数     
          "nonceStr": r.nonceStr,      //随机串     
          "package": r.package,
          "signType": "MD5",     //微信签名方式：     
          "paySign": r.paySign
        },
        function(res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
              // 使用以上方式判断前端返回,微信团队郑重提示：
              //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
              window.location.href = "/#/success/" + app_id + "/" + unionid
          }
        })
      }
      else {
        console.log(res);
      }
    })
  }

  render () {

    let select_huiyuan_idx = this.state.select_huiyuan_idx;
    let changeHuiyuan = this.changeHuiyuan.bind(this);
    let app_id = this.props.params.app_id;

    let headimgurl = this.state.headimgurl;
    let nickname = this.state.nickname;
    let user_no = this.state.user_no;

    return (
      <div className="bamboo-app" style={{minHeight: window.screen.availHeight + "px"}}>
        <div className="jihuoma-header">
          <img src={headimgurl == "" ? "https://www.juzizhi.cn/stylesheets/images/default_user.png" : headimgurl} />
          <p>{nickname}{user_no}</p>
        </div>
        <div className="jihuoma-content">
          <h3>适用于手机+iPad</h3>
          <div>
            {
              this.state.huiyuan_list.map(function (item, idx) {

                return <div 
                          href="javascript:void(0)" 
                          key={idx} 
                          data-id={item['_id']['$oid']} 
                          data-idx={idx}
                          onClick={changeHuiyuan}
                          className={select_huiyuan_idx == idx ? "huiyuan-buy-item huiyuan-click" : "huiyuan-buy-item"}
                  >
                  {
                    item.is_activity == 1 ? <span className="activity">{item.activity_message}</span> : ""
                  }
                  
                  <div className={item.is_activity == 1 ? 'title title-activity' : 'title'}>
                    <span>{item.sub_title}</span>
                    <span>￥{item.price}</span>
                  </div>
                  <div className="price">
                    <span>立减{item.true_price - item.price}元</span>
                    <span>原价{item.true_price}元</span>
                  </div>
                  {
                    item.huiyuan_type == 0 ?
                    <div className="tishi">可使用{item.ma_time_len == 0 ? "99年" : item.ma_time_len + "天"}，每天仅需{item.yuan}元</div>
                    : ""
                  }
                  
                </div>
              })
            }

          </div>
          
          <div className="huiyuan-quanyi">
            <div className="huiyuan-quanyi-title">会员权益</div>
            <div className="huiyuan-quanyi-list">
              {
                this.state.huiyuan_quanyi.map(function (item, idx) {
                  return <div>{item}</div>
                })
              }
            </div>
          </div>
        </div>

        <h3 className="zhuyi">
          注：本商品为虚拟内容服务，非特殊原因购买后不支持退订、退换。
        </h3>
        <a className="jihuoma-buy-button" href="javascript:void(0)" onClick={this.Pay.bind(this)}>立即开通</a>
      </div>
    )
  }
}

class Application extends React.Component {
  constructor () {
    super();
  }

  componentDidMount () {

  }

  render () {
    return (
      <div>
        {this.props.children ? this.props.children : <Index {...this.props}/>}
      </div>
    )
  }
}

export default Application;
